package org.example.sunrise;

import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.example.sunrise.core.Context;
import org.example.sunrise.core.SunriseFactory;
import org.example.sunrise.core.ViewEnum;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

public class SimpleSunriseFactory implements SunriseFactory {
    private static final String CONFIG_FILE = "sunrise.properties";
    private final Properties config = new Properties();
    private final Context ctx;
    private final Map<ViewEnum, Parent> views = new HashMap<>();
    private Parent currentView;

    public SimpleSunriseFactory(Stage stage) throws IOException {
        try (InputStream inputStream = Objects.requireNonNull(SimpleSunriseFactory.class.getResource(CONFIG_FILE)).openStream()) {
            config.load(inputStream);
        }
        this.ctx = new Context("植物大战僵尸", 800, 600, stage,this);
    }

    @Override
    public Parent getView(ViewEnum k) {
        Parent view = views.get(k);
        if (view == null) {
            view = createView(k);
            views.put(k, view);
        }
        currentView = view;
        return view;
    }

    @Override
    public Scene getScene() {
        return currentView.getScene();
    }

    @Override
    public void show(ViewEnum v) {
        getScene().setRoot(getView(v));
    }

    public Context getCtx() {
        return ctx;
    }

    private Parent createView(ViewEnum k) {
        String cls = config.getProperty(k.getName());
        try {
            Class<?> viewClass = Class.forName(cls);
            if (!Parent.class.isAssignableFrom(viewClass)) {
                throw new IllegalArgumentException("类 " + cls + " 不是 javafx.scene.Parent 的子类");
            }
            try {
                Constructor<?> constructor = viewClass.getDeclaredConstructor(Context.class);
                return (Parent) constructor.newInstance(ctx);
            } catch (NoSuchMethodException e) {
                Constructor<?> noArgConstructor = viewClass.getDeclaredConstructor();
                return (Parent) noArgConstructor.newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException |
                 ClassNotFoundException e) {
            throw new RuntimeException("无法创建视图实例: " + cls, e);
        }
    }
}
